package com.mindether.llyblog.controller;

import com.mindether.llyblog.pojo.ApiResponse;
import com.mindether.llyblog.pojo.Tag;
import com.mindether.llyblog.service.TagService;
import com.mindether.llyblog.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/tag")
@Controller
public class TagController {
    @Autowired
    private TagService tagService;

    @Autowired
    private IdWorker idWorker;

    @RequestMapping("/all")
    @ResponseBody
    public ApiResponse allTags(){
        List<Tag>  tags= tagService.findAllTags();

        return ApiResponse.ok().setData(tags).setMessage("查询成功");
    }

    @RequestMapping("/{id}")
    @ResponseBody
    public  ApiResponse findTagById(@PathVariable("id")String id){
        Tag tag=  tagService.getTagById(id);
        return ApiResponse.ok().setMessage("查询成功").setData(tag);
    }
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public  ApiResponse deleteTagById(@PathVariable("id")String id){
        tagService.delete(id);
        flushTags();
        return ApiResponse.ok().setMessage("删除成功");
    }
    //刷新标签
    private void flushTags(){
        ArticleController.allTags.clear();
        ArticleController.allTags.addAll(tagService.findAllTags());
    }

    @RequestMapping(value="/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public  ApiResponse updateTagById(@PathVariable("id")String id, @RequestBody Tag tag){
        tag.setId(id);
        tagService.update(tag);
        flushTags();
        return ApiResponse.ok().setMessage("更新成功");
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public  ApiResponse addTag(@RequestBody Tag tag){
        tag.setId(idWorker.nextId()+"");
        tagService.add(tag);
        flushTags();
        return ApiResponse.ok().setMessage("新增成功");
    }
}
